// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const $ = db.command.aggregate
const _ = db.command

// 查询所有诉求（限制用户沟通即可)
const queryAllChat = async function (params) {
  const wxContext = cloud.getWXContext()

  try {

    let chats = await db.collection('chat').aggregate()
      .match({
        userIds: _.in([wxContext.OPENID])
      })
      .lookup({
        from: "chatRecord",
        localField: '_id',
        foreignField: 'chatId',
        as: 'record'
      }).replaceRoot({
        newRoot: $.mergeObjects([{
          lastRecord: $.arrayElemAt(['$record', -1])
        }, '$$ROOT'])
      })
      .project({
        record: 0
      })
      .end()

    chats = chats.list

    // 移除自己的信息
    chats.forEach((item, index) => {

      item.chatUser.forEach((user, userIndex) => {
        if (user._openid === wxContext.OPENID) {
          item.chatUser.splice(userIndex, 1)
        }
      })

    })

    return chats

  } catch (error) {

    console.log('appealSave error' + error)

    return []
  }

}

module.exports = queryAllChat